<!DOCTYPE html>
<html lang="en">
<head>
        <meta charset="utf-8" />
        <title>Part.1.E.5.strings</title>
        <link rel="stylesheet" href="/theme/css/main.css" />

        <!--[if IE]>
            <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
        <![endif]-->
</head>

<body id="index" class="home">
        <header id="banner" class="body">
                <h1><a href="/">PythonTutorials </a></h1>
                <nav><ul>
                    <li><a href="/category/cpp.html">cpp</a></li>
                    <li class="active"><a href="/category/python.html">python</a></li>
                </ul>
                </nav>
        </header><!-- /#banner -->
<section id="content" class="body">
  <article>
    <header>
      <h1 class="entry-title">
        <a href="/Part.1.E.5.strings.html" rel="bookmark"
           title="Permalink to Part.1.E.5.strings">Part.1.E.5.strings</a></h1>
    </header>

    <div class="entry-content">
<footer class="post-info">
        <span>Mon 06 April 2020</span>
<span>| tags: <a href="/tag/python.html">python</a><a href="/tag/progarmming.html">progarmming</a><a href="/tag/excel.html">Excel</a></span>
</footer><!-- /.post-info -->      <h1>字符串</h1>
<p>在任何一本编程书籍之中，关于字符串的内容总是很长 —— 就好像每本英语语法书中，关于动词的内容总是占全部内容的至少三分之二。这也没什么办法，因为处理字符串是计算机程序中最普遍的需求 —— 因为程序的主要功能就是完成人机交互，人们所用的就是字符串而不是二进制数字。</p>
<p>在计算机里，所有的东西最终都要被转换成数值。又由于计算机靠的是电路，所以，最终只能处理 <code>1</code> 和 <code>0</code>，于是，最基本的数值是二进制；于是，连整数、浮点数字，都要最终转换成二进制数值。这就是为什么在所有编程语言中 <code>1.1 + 2.2</code> 并不是你所想象的 <code>3.3</code> 的原因。</p>
<div class="highlight"><pre><span></span><span class="mf">1.1</span> <span class="o">+</span> <span class="mf">2.2</span>
</pre></div>


<div class="highlight"><pre><span></span>3.3000000000000003
</pre></div>


<p>因为最终所有的值都要转换成二进制 —— 这时候，小数的精度就有损耗，多次浮点数字转换成二进制相互运算之后再从二进制转换为十进制之后返回的结果，精度损耗就更大了。因此，在计算机上，浮点数字的精度总有极限。有兴趣进一步可以看看<a href="https://docs.python.org/3/library/decimal.html">关于 decimal 模块的文档</a>。</p>
<p>字符串也一样。一个字符串由 0 个字符或者多个字符构成，它最终也要被转换成数值，再进一步被转换成二进制数值。空字符串的值是 <code>None</code>，即便是这个 <code>None</code> —— 也最终还是要被转换成二进制的 <code>0</code>。</p>
<h2>字符码表的转换</h2>
<p>很久以前，计算机的中央处理器最多只能够处理 8 位二进制数值，所以，那时候的计算机只能处理 256 个字符，即，2<sup>8</sup> 个字符。那个时候计算机所使用的码表叫 ASCII。现在计算机的中央处理器，大多是 64 位的，所以可以使用 2<sup>64</sup> 容量的码表，叫做 <a href="https://zh.wikipedia.org/wiki/Unicode">Unicode</a>。随着多年的收集，2018 年 6 月 5 日公布的 <code>11.0.0</code> 版本已经包含了 13 万个字符 —— 突破 10 万字符是在 2005 年<a href='#fn1' name='fn1b'><sup>[1]</sup></a>。</p>
<p>把单个字符转换成码值的函数是 <code>ord()</code>，它只接收单个字符，否则会报错；它返回该字符的  unicode 编码。与 <code>ord()</code> 相对的函数是 <code>chr()</code>，它接收且只接收一个整数作为参数，而后返回相应的字符。<code>ord()</code> 接收多个字符的话会报错。</p>
<div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">IPython.core.interactiveshell</span> <span class="kn">import</span> <span class="n">InteractiveShell</span>
<span class="n">InteractiveShell</span><span class="o">.</span><span class="n">ast_node_interactivity</span> <span class="o">=</span> <span class="s2">&quot;all&quot;</span>

<span class="nb">ord</span><span class="p">(</span><span class="s1">&#39;a&#39;</span><span class="p">)</span>
<span class="nb">chr</span><span class="p">(</span><span class="mi">122</span><span class="p">)</span>

<span class="nb">ord</span><span class="p">(</span><span class="s1">&#39;氅&#39;</span><span class="p">)</span>  <span class="c1"># 完了，汉字也有你不认识的吧？</span>
<span class="nb">chr</span><span class="p">(</span><span class="mi">25354</span><span class="p">)</span> <span class="c1"># 这个字估计你也不认识……</span>

<span class="c1"># ord(&#39;Python&#39;) # 这一句会报错</span>
</pre></div>


<div class="highlight"><pre><span></span>97
&#39;z&#39;
27653
&#39;挊&#39;
</pre></div>


<h2>字符串的标示</h2>
<p>标示一个字符串，有 4 种方式，用单引号、用双引号，用三个单引号或者三个双引号：</p>
<div class="highlight"><pre><span></span><span class="s1">&#39;Simple is better than complex.&#39;</span> <span class="c1"># 用单引号</span>
</pre></div>


<div class="highlight"><pre><span></span>&#39;Simple is better than complex.&#39;
</pre></div>


<div class="highlight"><pre><span></span><span class="s2">&quot;Simple is better than complex.&quot;</span> <span class="c1"># 用双引号</span>
</pre></div>


<div class="highlight"><pre><span></span>&#39;Simple is better than complex.&#39;
</pre></div>


<div class="highlight"><pre><span></span><span class="c1"># 用三个单引号。注意输出结果中的 \n</span>
<span class="c1"># 这个字符串，看起来是两行，保存在内存或者变量之中的时候，</span>
<span class="c1"># 是一整串，其中的换行是用 \n 表示的。</span>
<span class="sd">&#39;&#39;&#39;</span>
<span class="sd">Simple is better than complex.</span>
<span class="sd">Complex is better than complicated.</span>
<span class="sd">&#39;&#39;&#39;</span>
</pre></div>


<div class="highlight"><pre><span></span>&#39;\nSimple is better than complex.\nComplex is better than complicated.\n&#39;
</pre></div>


<div class="highlight"><pre><span></span><span class="c1">#用三个双引号。注意输出结果中的 \n</span>
<span class="sd">&quot;&quot;&quot;</span>
<span class="sd">Simple is better than complex.</span>
<span class="sd">Complex is better than complicated.</span>
<span class="sd">&quot;&quot;&quot;</span>
</pre></div>


<div class="highlight"><pre><span></span>&#39;\nSimple is better than complex.\nComplex is better than complicated.\n&#39;
</pre></div>


<div class="highlight"><pre><span></span><span class="k">print</span><span class="p">(</span>
<span class="sd">&quot;&quot;&quot;</span>
<span class="sd">Simple is better than complex.</span>
<span class="sd">Complex is better than complicated.</span>
<span class="sd">&quot;&quot;&quot;</span>
<span class="p">)</span> <span class="c1">#用 print() 输出的时候，\n 就是不可见字符，字符串本身如下：</span>
<span class="c1"># &#39;\nSimple is better than complex.\nComplex is better than complicated.\n&#39;</span>
<span class="c1"># 其中的 \n 被打印出来的时候显示成换行</span>
</pre></div>


<div class="highlight"><pre><span></span>Simple is better than complex.
Complex is better than complicated.
</pre></div>


<h2>字符串与数值之间的转换</h2>
<p>由数字构成的字符串，可以被转换成数值，转换整数用 <code>int()</code>，转换浮点数字用 <code>float()</code>。</p>
<p>与之相对，用 <code>str()</code>，可以将数值转换成字符串类型。</p>
<p>注意，int() 在接收字符串为参数的时候，只能做整数转换。下面代码最后一行会报错：</p>
<div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">IPython.core.interactiveshell</span> <span class="kn">import</span> <span class="n">InteractiveShell</span>
<span class="n">InteractiveShell</span><span class="o">.</span><span class="n">ast_node_interactivity</span> <span class="o">=</span> <span class="s2">&quot;all&quot;</span>

<span class="nb">int</span><span class="p">(</span><span class="s1">&#39;3&#39;</span><span class="p">)</span>
<span class="nb">float</span><span class="p">(</span><span class="s1">&#39;3&#39;</span><span class="p">)</span>
<span class="nb">str</span><span class="p">(</span><span class="mf">3.1415926</span><span class="p">)</span>
<span class="c1"># int(&#39;3.1415926&#39;) # 这一行会报错</span>
</pre></div>


<div class="highlight"><pre><span></span>3
3.0
&#39;3.1415926&#39;
</pre></div>


<p><code>input()</code> 这个内建函数的功能是接收用户的键盘输入，而后将其作为字符串返回。它可以接收一个字符串作为参数，在接收用户键盘输入之前，会把这个参数输出到屏幕，作为给用户的提示语。这个参数是可选参数，直接写 <code>input()</code>，即，没有提供参数，那么它在要求用户输入的时候，就没有提示语。</p>
<p>以下代码会报错，因为 <code>age &lt; 18</code> 不是合法的逻辑表达式，因为 <code>age</code> 是由 <code>input()</code> 传递过来的字符串；于是，它不是数字，那么它不可以与数字比较……</p>
<div class="highlight"><pre><span></span><span class="n">age</span> <span class="o">=</span> <span class="nb">input</span><span class="p">(</span><span class="s1">&#39;Please tell me your age: &#39;</span><span class="p">)</span>
<span class="k">if</span> <span class="n">age</span> <span class="o">&lt;</span> <span class="mi">18</span><span class="p">:</span>
    <span class="k">print</span><span class="p">(</span><span class="s1">&#39;I can not sell you drinks...&#39;</span><span class="p">)</span>
<span class="k">else</span><span class="p">:</span>
    <span class="k">print</span><span class="p">(</span><span class="s1">&#39;Have a nice drink!&#39;</span><span class="p">)</span>
</pre></div>


<div class="highlight"><pre><span></span>Please tell me your age:  19

---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

&lt;ipython-input-9-0573fe379e83&gt; in &lt;module&gt;
      1 age = input(&#39;Please tell me your age: &#39;)
----&gt; 2 if age &lt; 18:
      3     print(&#39;I can not sell you drinks...&#39;)
      4 else:
      5     print(&#39;Have a nice drink!&#39;)

TypeError: &#39;&lt;&#39; not supported between instances of &#39;str&#39; and &#39;int&#39;
</pre></div>


<p>要改成这样才可能行：
为什么是可能行而不是一定行？如果用户 <code>input</code> 键盘输入的是 <code>eighteen</code> 或者 <code>十八</code> 等，依然会导致 <code>int()</code> 失败并得到 <code>ValueError</code> 的报错。用户输入的不可控，可能会导致千奇百怪的报错。但在这里，我们先简化处理，在引导语中加入一个正确的示例并默认用户会按引导语正确输入。</p>
<div class="highlight"><pre><span></span><span class="n">age</span> <span class="o">=</span> <span class="nb">int</span><span class="p">(</span><span class="nb">input</span><span class="p">(</span><span class="s1">&#39;&#39;&#39;Please tell me your age:</span>
<span class="s1"> an int number , e.g: 22</span>
<span class="s1">&#39;&#39;&#39;</span><span class="p">))</span>
<span class="k">if</span> <span class="n">age</span> <span class="o">&lt;</span> <span class="mi">18</span><span class="p">:</span>
    <span class="k">print</span><span class="p">(</span><span class="s1">&#39;I can not sell you drinks...&#39;</span><span class="p">)</span>
<span class="k">else</span><span class="p">:</span>
    <span class="k">print</span><span class="p">(</span><span class="s1">&#39;Have a nice drink!&#39;</span><span class="p">)</span>
</pre></div>


<div class="highlight"><pre><span></span>Please tell me your age:  19
Have a nice drink!
</pre></div>


<p><strong>注意</strong>：如果你用来浏览当前 <code>.ipynb</code> 文件的是那个桌面 App <a href="https://nteract.io/">Nteract</a>，它目前不支持 input() 这个函数的调用……</p>
<h2>转义符</h2>
<p>有一个重要的字符，叫做 “转义符”，<code>\</code>，也有的地方把它称为 “脱字符”，因为它的英文原文是 <em>Escaping Character</em>。它本身不被当作字符，你要想在字符串里含有这个字符，得这样写 <code>\\</code>：</p>
<div class="highlight"><pre><span></span><span class="s1">&#39;</span><span class="se">\\</span><span class="s1">&#39;</span>
</pre></div>


<div class="highlight"><pre><span></span>&#39;\\&#39;
</pre></div>


<div class="highlight"><pre><span></span><span class="s1">&#39;</span><span class="se">\&#39;</span>
</pre></div>


<div class="highlight"><pre><span></span>  File &quot;&lt;ipython-input-10-d44a383620ab&gt;&quot;, line 1
    &#39;\&#39;
       ^
SyntaxError: EOL while scanning string literal
</pre></div>


<p>上面这一行报错信息是 <code>SyntaxError: EOL while scanning string literal</code>。这是因为 <code>\'</code> 表示的是单引号字符 <code>'</code>（Literal）—— 是可被输出到屏幕的 <code>'</code>，而不是用来标示字符串的那个 <code>'</code> —— 别急，无论哪个初学者第一次读到前面的句子都觉得有点莫名其妙…… —— 于是，Python 编译器扫描这个 “字符串” 的时候，还没找到标示字符串末尾的另外一个 <code>'</code> 的时候就读到了 <code>EOL</code>（End Of Line）。</p>
<p>如果你想输出这么个字符串，<code>He said, it's fine.</code>，如果用双引号扩起来 <code>"</code> 倒没啥问题，但是如果用单引号扩起来就麻烦了，因为编译器会把 <code>it</code> 后面的那个单引号 <code>'</code> 当作字符串结尾。</p>
<div class="highlight"><pre><span></span><span class="s1">&#39;He said, it&#39;</span><span class="n">s</span> <span class="n">fine</span><span class="o">.</span><span class="s1">&#39;</span>
</pre></div>


<div class="highlight"><pre><span></span>  File &quot;&lt;ipython-input-11-2bcf2ca6dd95&gt;&quot;, line 1
    &#39;He said, it&#39;s fine.&#39;
                 ^
SyntaxError: invalid syntax
</pre></div>


<p>于是你就得用转义符 <code>\</code>：</p>
<div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">IPython.core.interactiveshell</span> <span class="kn">import</span> <span class="n">InteractiveShell</span>
<span class="n">InteractiveShell</span><span class="o">.</span><span class="n">ast_node_interactivity</span> <span class="o">=</span> <span class="s2">&quot;all&quot;</span>

<span class="c1"># 要么你这么写：</span>
<span class="s1">&#39;He said, it</span><span class="se">\&#39;</span><span class="s1">s fine.&#39;</span>
<span class="c1"># 要么你这么写：</span>
<span class="s2">&quot;He said, it&#39;s fine.&quot;</span>
<span class="c1"># 要么，不管用单引号还是双引号标示字符串，都习惯于用 \&#39; 和 \&quot; 书写属于字符串内部的引号……</span>
<span class="s2">&quot;He said, it</span><span class="se">\&#39;</span><span class="s2">s fine.&quot;</span>
</pre></div>


<div class="highlight"><pre><span></span>&quot;He said, it&#39;s fine.&quot;
&quot;He said, it&#39;s fine.&quot;
&quot;He said, it&#39;s fine.&quot;
</pre></div>


<p>转义符号 <code>\</code> 的另外两个常用形式是和 <code>t</code>、<code>n</code> 连起来用，<code>\t</code> 代表制表符（就是用 TAB <code>⇥</code> 键敲出来的东西），<code>\n</code> 代表换行符（就是用 Enter <code>⏎</code> 敲出来的东西）。</p>
<p>由于历史原因，Linux/Mac/Windows 操作系统中，换行符号的使用各不相同。Unix 类操作系统（包括现在的 MacOS），用的是 <code>\n</code>；Windows 用的是 <code>\r\n</code>，早期苹果公司的 Macintosh 用的是 <code>\r</code>（参见 <a href="https://en.wikipedia.org/wiki/Newline">Wikipedia: Newline</a>）。</p>
<p>所以，一个字符串，有两种形式，<strong>raw</strong> 和 <strong>presentation</strong>，在后者中，<code>\t</code> 被转换成制表符，<code>\n</code> 被转换成换行。</p>
<p>在写程序的过程中，我们在代码中写的是 <em>raw</em>，而例如当我们调用 <code>print()</code> 将字符串输出到屏幕上时，是 <em>presentation</em>：</p>
<div class="highlight"><pre><span></span><span class="n">s</span> <span class="o">=</span> <span class="s2">&quot;He said, it</span><span class="se">\&#39;</span><span class="s2">s fine.&quot;</span> <span class="c1"># raw</span>
<span class="k">print</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>                   <span class="c1"># presentation</span>
</pre></div>


<div class="highlight"><pre><span></span>He said, it&#39;s fine.
</pre></div>


<p>以后有时间去看看这两个内建函数，能了解更多细节：</p>
<blockquote>
<ul>
<li><strong>ascii</strong>(<em>object</em>) https://docs.python.org/3/library/functions.html#ascii</li>
<li><strong>repr</strong>(<em>object</em>) https://docs.python.org/3/library/functions.html#repr</li>
</ul>
</blockquote>
<h2>字符串的操作符</h2>
<p>字符串可以用空格 <code>' '</code> 或者 <code>+</code> 拼接：</p>
<div class="highlight"><pre><span></span><span class="s1">&#39;Hey!&#39;</span> <span class="o">+</span> <span class="s1">&#39; &#39;</span> <span class="o">+</span> <span class="s1">&#39;You!&#39;</span> <span class="c1"># 使用操作符 +</span>
</pre></div>


<div class="highlight"><pre><span></span>&#39;Hey! You!&#39;
</pre></div>


<div class="highlight"><pre><span></span><span class="s1">&#39;Hey!&#39;</span> <span class="s1">&#39;You!&#39;</span> <span class="c1"># 空格与 + 的作用是相同的。</span>
</pre></div>


<div class="highlight"><pre><span></span>&#39;Hey!You!&#39;
</pre></div>


<p>字符串还可以与整数倍操作符 <code>*</code> 操作，<code>'Ha' * 3</code> 的意思是说，把字符串 <code>'Ha'</code> 复制三遍：</p>
<div class="highlight"><pre><span></span><span class="s1">&#39;Ha&#39;</span> <span class="o">*</span> <span class="mi">3</span>
</pre></div>


<div class="highlight"><pre><span></span>&#39;HaHaHa&#39;
</pre></div>


<div class="highlight"><pre><span></span><span class="s1">&#39;3.14&#39;</span> <span class="o">*</span> <span class="mi">3</span>
</pre></div>


<div class="highlight"><pre><span></span>&#39;3.143.143.14&#39;
</pre></div>


<p>字符串还可以用 <code>in</code> 和 <code>not in</code> 操作符 —— 看看某个字符或者字符串是否被包含在某个字符串中，返回的是布尔值：</p>
<div class="highlight"><pre><span></span><span class="s1">&#39;o&#39;</span> <span class="ow">in</span> <span class="s1">&#39;Hey, You!&#39;</span>
</pre></div>


<div class="highlight"><pre><span></span>True
</pre></div>


<h2>字符串的索引</h2>
<p>字符串是由一系列的字符构成的。在 Python 当中，有一个容器（Container）的概念，这个概念前面提到过，后面还会深入讲解。现在需要知道的是，字符串是容器的一种；容器可分为两种，有序的和无序的 —— 字符串属于<strong>有序容器</strong>。</p>
<p>字符串里的每个字符，对应着一个从 <code>0</code> 开始的索引。比较有趣的是，索引可以是负数：</p>
<table>
<thead>
<tr>
<th>0</th>
<th>1</th>
<th>2</th>
<th>3</th>
<th>4</th>
<th>5</th>
</tr>
</thead>
<tbody>
<tr>
<td>P</td>
<td>y</td>
<td>t</td>
<td>h</td>
<td>o</td>
<td>n</td>
</tr>
<tr>
<td>-6</td>
<td>-5</td>
<td>-4</td>
<td>-3</td>
<td>-2</td>
<td>-1</td>
</tr>
</tbody>
</table>
<div class="highlight"><pre><span></span><span class="n">s</span> <span class="o">=</span> <span class="s1">&#39;Python&#39;</span>
<span class="k">for</span> <span class="n">char</span> <span class="ow">in</span> <span class="n">s</span><span class="p">:</span>
    <span class="k">print</span><span class="p">(</span><span class="n">s</span><span class="o">.</span><span class="n">index</span><span class="p">(</span><span class="n">char</span><span class="p">),</span> <span class="n">char</span><span class="p">)</span>
</pre></div>


<div class="highlight"><pre><span></span>0 P
1 y
2 t
3 h
4 o
5 n
</pre></div>


<p>对于有序容器中的元素 —— 字符串就是字符的有序容器 —— 由于它们是有索引的，所以我们可以根据索引提取容器中的值，你可以把 <code>[]</code> 当作是有序容器的操作符之一，我们姑且将其称为 “<em>索引操作符</em>”。注意以下代码第 3 行中，<code>s</code> 后面的 <code>[]</code>，以及里面的变量 <code>i</code>：</p>
<div class="highlight"><pre><span></span><span class="n">s</span> <span class="o">=</span> <span class="s1">&#39;Python&#39;</span>
<span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">s</span><span class="p">)):</span>
    <span class="k">print</span><span class="p">(</span><span class="n">s</span><span class="p">[</span><span class="n">i</span><span class="p">])</span>

<span class="c1">#上面的代码仅是为了演示索引操作符的使用，更简洁的写法是：</span>
<span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="n">s</span><span class="p">:</span>
    <span class="k">print</span><span class="p">(</span><span class="n">i</span><span class="p">)</span>
</pre></div>


<div class="highlight"><pre><span></span>P
y
t
h
o
n
</pre></div>


<p>我们可以使用<em>索引操作符</em>根据<em>索引</em><strong>提取</strong>字符串这个<em>有序容器</em>中的<em>一个或多个元素</em>，即，其中的字符或字符串。这个 “提取” 的动作有个专门的术语，叫做 “Slicing”（切片）。索引操作符 <code>[]</code> 中可以有一个、两个或者三个整数参数，如果有两个参数，需要用 <code>:</code> 隔开。它最终可以写成以下 4 种形式：</p>
<blockquote>
<ul>
<li><code>s[index]</code> —— 返回索引值为 <code>index</code> 的那个字符</li>
<li><code>s[start:]</code> —— 返回从索引值为 <code>start</code> 开始一直到字符串末尾的所有字符</li>
<li><code>s[start:stop]</code> —— 返回从索引值为 <code>start</code> 开始一直到索引值为 <code>stop</code> 的那个字符<em>之前</em>的所有字符</li>
<li><code>s[:stop]</code> —— 返回从字符串开头一直到索引值为 <code>stop</code> 的那个字符<em>之前</em>的所有字符</li>
<li><code>s[start:stop:step]</code> —— 返回从索引值为 <code>start</code> 开始一直到索引值为 <code>stop</code> 的那个字符<em>之前</em>的，以 <code>step</code> 为步长提取的所有字符</li>
</ul>
</blockquote>
<p>提醒：无论是 <code>range(1,2)</code>，或者 <code>random.randrange(100, 1000)</code> 又或者 <code>s[start:stop]</code> 都有一个相似的规律，包含左侧的 <code>1</code>, <code>100</code>, <code>start</code>，不包含右侧的 <code>2</code>, <code>1000</code>, <code>stop</code>。</p>
<div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">IPython.core.interactiveshell</span> <span class="kn">import</span> <span class="n">InteractiveShell</span>
<span class="n">InteractiveShell</span><span class="o">.</span><span class="n">ast_node_interactivity</span> <span class="o">=</span> <span class="s2">&quot;all&quot;</span>

<span class="n">s</span> <span class="o">=</span> <span class="s1">&#39;Python&#39;</span>
<span class="n">s</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span>
<span class="n">s</span><span class="p">[</span><span class="mi">2</span><span class="p">:]</span>
<span class="n">s</span><span class="p">[</span><span class="mi">2</span><span class="p">:</span><span class="mi">5</span><span class="p">]</span>
<span class="n">s</span><span class="p">[:</span><span class="mi">5</span><span class="p">]</span>
<span class="n">s</span><span class="p">[</span><span class="mi">1</span><span class="p">:</span><span class="mi">5</span><span class="p">:</span><span class="mi">2</span><span class="p">]</span>
</pre></div>


<div class="highlight"><pre><span></span>&#39;y&#39;
&#39;thon&#39;
&#39;tho&#39;
&#39;Pytho&#39;
&#39;yh&#39;
</pre></div>


<h2>处理字符串的内建函数</h2>
<p><a href="https://docs.python.org/3/library/functions.html#slice">Python 内建函数</a>中，把字符串当做处理对象的有：<code>ord()</code>、<code>input()</code>、<code>int()</code>、<code>float()</code>、<code>len()</code>、<code>print()</code>。再次注意，<code>ord()</code> 只接收单个字符为参数。</p>
<div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">IPython.core.interactiveshell</span> <span class="kn">import</span> <span class="n">InteractiveShell</span>
<span class="n">InteractiveShell</span><span class="o">.</span><span class="n">ast_node_interactivity</span> <span class="o">=</span> <span class="s2">&quot;all&quot;</span>

<span class="nb">ord</span><span class="p">(</span><span class="s1">&#39;</span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">)</span>
<span class="nb">ord</span><span class="p">(</span><span class="s1">&#39;</span><span class="se">\t</span><span class="s1">&#39;</span><span class="p">)</span>
<span class="nb">ord</span><span class="p">(</span><span class="s1">&#39;</span><span class="se">\r</span><span class="s1">&#39;</span><span class="p">)</span>
<span class="nb">chr</span><span class="p">(</span><span class="mi">65</span><span class="p">)</span> <span class="c1"># 与 ord() 相对的函数</span>
<span class="n">s</span> <span class="o">=</span> <span class="nb">input</span><span class="p">(</span><span class="s1">&#39;请照抄一遍这个数字 3.14: &#39;</span><span class="p">)</span>
<span class="nb">int</span><span class="p">(</span><span class="s1">&#39;3&#39;</span><span class="p">)</span>
<span class="c1"># int(s) 这一句会报错…… 所以暂时注释掉了</span>
<span class="nb">float</span><span class="p">(</span><span class="n">s</span><span class="p">)</span> <span class="o">*</span> <span class="mi">9</span>
<span class="nb">len</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
<span class="k">print</span><span class="p">(</span><span class="n">s</span><span class="o">*</span><span class="mi">3</span><span class="p">)</span>
</pre></div>


<div class="highlight"><pre><span></span>10
9
13
&#39;A&#39;
请照抄一遍这个数字 3.14:  3.14
3
28.26
4
3.143.143.14
</pre></div>


<h2>处理字符串的 Method</h2>
<p>在 Python 中，字符串是一个<strong>对象</strong> —— 更准确地讲，是 str 类（<code>Class str</code>）的对象。</p>
<p>第一部分尚未读完的你，暂时不用了解对象究竟是什么；只需要知道的是，一个对象的内部有很多函数…… 这些写在对象内部的函数，有个专门的名称，类的<strong>方法</strong>（Method）。问题在于，在讲解编程的内容里，“方法” 这个词（比如，处理数值的<em>方法</em>是……）随处可见；所以，<strong>为了避免歧义</strong>，以后的文字里，提到 “类的方法” 的时候，直接用 <strong>Method</strong> 这个英文单词……</p>
<p>字符串有很多可以调用的 Methods。以下介绍的 <code>str</code> Methods，在官方文档 "<a href="https://docs.python.org/3/library/stdtypes.html#text-sequence-type-str">Text Sequence Type</a>" 中都可以找到。</p>
<p>调用 str 类的 Methods 是使用 <code>.</code> 这个符号，比如：</p>
<div class="highlight"><pre><span></span><span class="s1">&#39;Python&#39;</span><span class="o">.</span><span class="n">upper</span><span class="p">()</span>
</pre></div>


<h3>大小写转换</h3>
<p>转换字符串大小写的是 <code>str.upper()</code>、<code>str.lower()</code> 和 <code>str.swapcase()</code>，以及 <code>str.casefold()</code>；另外，还有专门针对行首字母大写的 <code>str.capitalize()</code> 和针对每个词的首字母大写的 <code>str.title()</code>：</p>
<div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">IPython.core.interactiveshell</span> <span class="kn">import</span> <span class="n">InteractiveShell</span>
<span class="n">InteractiveShell</span><span class="o">.</span><span class="n">ast_node_interactivity</span> <span class="o">=</span> <span class="s2">&quot;all&quot;</span>

<span class="s1">&#39;Now is better than never.&#39;</span><span class="o">.</span><span class="n">upper</span><span class="p">()</span>

<span class="c1"># 在 Python 命令行工具之中，单个下划线，是个特殊变量；</span>
<span class="c1"># 保存着最近的语句或者表达式的结果</span>
<span class="c1"># 上一个 Cell 执行过后，_ 中保存着 &#39;NOW IS BETTER THAN NEVER.&#39;</span>

<span class="n">_</span><span class="o">.</span><span class="n">lower</span><span class="p">()</span>
</pre></div>


<div class="highlight"><pre><span></span>&#39;NOW IS BETTER THAN NEVER.&#39;

&#39;now is better than never.&#39;
</pre></div>


<div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">IPython.core.interactiveshell</span> <span class="kn">import</span> <span class="n">InteractiveShell</span>
<span class="n">InteractiveShell</span><span class="o">.</span><span class="n">ast_node_interactivity</span> <span class="o">=</span> <span class="s2">&quot;all&quot;</span>

<span class="c1"># casefold() 也是转换成小写，但它能处理更多欧洲语言字符</span>

<span class="s1">&#39;ß&#39;</span><span class="o">.</span><span class="n">casefold</span><span class="p">()</span>           <span class="c1"># 德语字符中，大写 ß 的小写形式是 ss</span>
<span class="nb">len</span><span class="p">(</span><span class="s1">&#39;ß&#39;</span><span class="o">.</span><span class="n">casefold</span><span class="p">())</span>
<span class="s1">&#39;ß&#39;</span><span class="o">.</span><span class="n">lower</span><span class="p">()</span>              <span class="c1"># lower() 对这类字符无能为力……</span>
<span class="nb">len</span><span class="p">(</span><span class="s1">&#39;ß&#39;</span><span class="o">.</span><span class="n">lower</span><span class="p">())</span>
<span class="c1"># casefold</span>
<span class="s1">&#39;</span><span class="se">\u0132</span><span class="s1">&#39;</span>                <span class="c1"># Ĳ 这个字符的 Unicode 编码</span>
<span class="s1">&#39;</span><span class="se">\u0132</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">casefold</span><span class="p">()</span>
<span class="s1">&#39;</span><span class="se">\u0132</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">lower</span><span class="p">()</span>        <span class="c1"># 对这个字符来说，lower() 和 casefold 的效果一样</span>
<span class="nb">len</span><span class="p">(</span><span class="s1">&#39;</span><span class="se">\u0132</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">casefold</span><span class="p">())</span>

<span class="c1"># 这是一篇有用的文章：</span>
<span class="c1"># Truths programmers should know about case</span>
<span class="c1"># https://www.b-list.org/weblog/2018/nov/26/case/</span>
</pre></div>


<div class="highlight"><pre><span></span>&#39;ss&#39;
2
&#39;ß&#39;
1
&#39;Ĳ&#39;
&#39;ĳ&#39;
&#39;ĳ&#39;
1
</pre></div>


<div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">IPython.core.interactiveshell</span> <span class="kn">import</span> <span class="n">InteractiveShell</span>
<span class="n">InteractiveShell</span><span class="o">.</span><span class="n">ast_node_interactivity</span> <span class="o">=</span> <span class="s2">&quot;all&quot;</span>

<span class="n">s</span> <span class="o">=</span> <span class="s1">&#39;Now is better than never.&#39;</span>
<span class="n">s</span><span class="o">.</span><span class="n">capitalize</span><span class="p">()</span> <span class="c1"># 句首字母大写</span>
<span class="n">s</span><span class="o">.</span><span class="n">title</span><span class="p">()</span> <span class="c1"># 每个单词首字母大写</span>
</pre></div>


<div class="highlight"><pre><span></span>&#39;Now is better than never.&#39;
&#39;Now Is Better Than Never.&#39;
</pre></div>


<div class="highlight"><pre><span></span><span class="n">s</span> <span class="o">=</span> <span class="s1">&#39;Now is better than never.&#39;</span>
<span class="n">s</span><span class="o">.</span><span class="n">swapcase</span><span class="p">()</span> <span class="c1"># 逐个字符更替大小写</span>
<span class="n">s</span><span class="o">.</span><span class="n">title</span><span class="p">()</span>
<span class="n">s</span><span class="o">.</span><span class="n">title</span><span class="p">()</span><span class="o">.</span><span class="n">swapcase</span><span class="p">()</span>
</pre></div>


<div class="highlight"><pre><span></span>&#39;nOW IS BETTER THAN NEVER.&#39;
&#39;Now Is Better Than Never.&#39;
&#39;nOW iS bETTER tHAN nEVER.&#39;
</pre></div>


<p>另外，还有个 <code>str.encode()</code> 在处理非英文字符串（比如中文）的时候，经常会用到：</p>
<div class="highlight"><pre><span></span><span class="c1"># str.encode(encoding=&quot;utf-8&quot;, errors=&quot;strict&quot;)</span>
<span class="c1"># 关于更多可能的 encoding list, 请参阅：</span>
<span class="c1"># https://docs.python.org/3/library/codecs.html#standard-encodings</span>
<span class="n">s</span> <span class="o">=</span> <span class="s1">&#39;简单优于复杂。&#39;</span>
<span class="n">s</span><span class="o">.</span><span class="n">encode</span><span class="p">()</span>
</pre></div>


<div class="highlight"><pre><span></span>b&#39;\xe7\xae\x80\xe5\x8d\x95\xe4\xbc\x98\xe4\xba\x8e\xe5\xa4\x8d\xe6\x9d\x82\xe3\x80\x82&#39;
</pre></div>


<h3>搜索与替换</h3>
<p>让我们从 <code>str.count()</code> 这个搜寻子字符串出现次数的 Method（即，<code>str</code> 这个 <code>Class</code> 中定义的函数）开始。</p>
<p>官方文档是这么写的：</p>
<blockquote>
<p><code>str.count(sub[,start[,end]])</code></p>
</blockquote>
<p>下面的函数说明加了默认值，以便初次阅读更容易理解：</p>
<blockquote>
<p><code>str.count(sub [,start=0[, end=len(str)]])</code></p>
</blockquote>
<p>这里的方括号 <code>[]</code> 表示该参数可选；方括号里再次嵌套了一个方括号，这个意思是说，在这个可选参数 <code>start</code> 出现的情况下，还可以再有一个可选参数 <code>end</code>；</p>
<p>而 <code>=</code> 表示该参数有个默认值。上述这段说明如果你感到熟悉的话，说明前面的内容确实阅读到位了…… 与大量 “前置引用” 相伴随的是知识点的重复出现。</p>
<blockquote>
<ul>
<li>只给定 <code>sub</code> 一个参数的话，于是从第一个字符开始搜索到字符串结束；</li>
<li>如果，随后给定了一个可选参数的话，那么它是 <code>start</code>，于是从 <code>start</code> 开始，搜索到字符串结束；</li>
<li>如果 <code>start</code> 之后还有参数的话，那么它是 <code>end</code>；于是从 <code>start</code> 开始，搜索到 <code>end - 1</code> 结束（即不包含索引值为 <code>end</code> 的那个字符）。</li>
</ul>
<p>返回值为字符串中 <code>sub</code> 出现的次数。</p>
</blockquote>
<p>注意：字符串中第一个字符的索引值是 <code>0</code>。</p>
<div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">IPython.core.interactiveshell</span> <span class="kn">import</span> <span class="n">InteractiveShell</span>
<span class="n">InteractiveShell</span><span class="o">.</span><span class="n">ast_node_interactivity</span> <span class="o">=</span> <span class="s2">&quot;all&quot;</span>

<span class="n">s</span> <span class="o">=</span> <span class="s2">&quot;&quot;&quot;Simple is better than complex.</span>
<span class="s2">Complex is better than complicated.&quot;&quot;&quot;</span>
<span class="n">s</span><span class="o">.</span><span class="n">lower</span><span class="p">()</span><span class="o">.</span><span class="n">count</span><span class="p">(</span><span class="s1">&#39;mp&#39;</span><span class="p">)</span>
<span class="n">s</span><span class="o">.</span><span class="n">lower</span><span class="p">()</span><span class="o">.</span><span class="n">count</span><span class="p">(</span><span class="s1">&#39;mp&#39;</span><span class="p">,</span> <span class="mi">10</span><span class="p">)</span>
<span class="n">s</span><span class="o">.</span><span class="n">lower</span><span class="p">()</span><span class="o">.</span><span class="n">count</span><span class="p">(</span><span class="s1">&#39;mp&#39;</span><span class="p">,</span> <span class="mi">10</span><span class="p">,</span> <span class="mi">30</span><span class="p">)</span>
</pre></div>


<div class="highlight"><pre><span></span>4
3
1
</pre></div>


<p>以下是 <code>str</code> 的搜索与替换的 Methods：<code>str.find()</code>, <code>str.rfind()</code>, <code>str.index()</code> 的示例：</p>
<div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">IPython.core.interactiveshell</span> <span class="kn">import</span> <span class="n">InteractiveShell</span>
<span class="n">InteractiveShell</span><span class="o">.</span><span class="n">ast_node_interactivity</span> <span class="o">=</span> <span class="s2">&quot;all&quot;</span>

<span class="c1"># str.find(sub[, start[, end]])</span>
<span class="k">print</span><span class="p">(</span><span class="s1">&#39;Example of str.find():&#39;</span><span class="p">)</span>
<span class="n">s</span> <span class="o">=</span> <span class="s2">&quot;&quot;&quot;Simple is better than complex.</span>
<span class="s2">Complex is better than complicated.&quot;&quot;&quot;</span>
<span class="n">s</span><span class="o">.</span><span class="n">lower</span><span class="p">()</span><span class="o">.</span><span class="n">find</span><span class="p">(</span><span class="s1">&#39;mpl&#39;</span><span class="p">)</span>
<span class="n">s</span><span class="o">.</span><span class="n">lower</span><span class="p">()</span><span class="o">.</span><span class="n">find</span><span class="p">(</span><span class="s1">&#39;mpl&#39;</span><span class="p">,</span> <span class="mi">10</span><span class="p">)</span>
<span class="n">s</span><span class="o">.</span><span class="n">lower</span><span class="p">()</span><span class="o">.</span><span class="n">find</span><span class="p">(</span><span class="s1">&#39;mpl&#39;</span><span class="p">,</span> <span class="mi">10</span><span class="p">,</span> <span class="mi">20</span><span class="p">)</span> <span class="c1"># 没有找到就返回 -1</span>
<span class="k">print</span><span class="p">()</span>

<span class="k">print</span><span class="p">(</span><span class="s1">&#39;Example of str.rfind():&#39;</span><span class="p">)</span>
<span class="c1"># str.rfind(sub[, start[, end]])</span>
<span class="c1"># rfind() 返回最后 sub 出现的那次的位置；find()是最早的那次</span>
<span class="n">s</span><span class="o">.</span><span class="n">lower</span><span class="p">()</span><span class="o">.</span><span class="n">rfind</span><span class="p">(</span><span class="s1">&#39;mpl&#39;</span><span class="p">)</span>
<span class="n">s</span><span class="o">.</span><span class="n">lower</span><span class="p">()</span><span class="o">.</span><span class="n">rfind</span><span class="p">(</span><span class="s1">&#39;mpl&#39;</span><span class="p">,</span> <span class="mi">10</span><span class="p">)</span>
<span class="n">s</span><span class="o">.</span><span class="n">lower</span><span class="p">()</span><span class="o">.</span><span class="n">rfind</span><span class="p">(</span><span class="s1">&#39;mpl&#39;</span><span class="p">,</span> <span class="mi">10</span><span class="p">,</span> <span class="mi">20</span><span class="p">)</span> <span class="c1"># 没有找到就返回 -1</span>
<span class="k">print</span><span class="p">()</span>

<span class="k">print</span><span class="p">(</span><span class="s1">&#39;Example of str.index():&#39;</span><span class="p">)</span>
<span class="c1"># str.index(sub[, start[, end]])</span>
<span class="c1"># 作用与 find() 相同，但如果没找到的话，会触发 ValueError 异常</span>
<span class="c1"># https://docs.python.org/3/library/exceptions.html#ValueError</span>
<span class="n">s</span><span class="o">.</span><span class="n">lower</span><span class="p">()</span><span class="o">.</span><span class="n">index</span><span class="p">(</span><span class="s1">&#39;mpl&#39;</span><span class="p">)</span>
<span class="c1"># str.rindex(sub[, start[, end]])</span>
<span class="c1"># 作用与 rfind() 相同，但如果没找到的话，会触发 ValueError 异常</span>
<span class="n">s</span><span class="o">.</span><span class="n">lower</span><span class="p">()</span><span class="o">.</span><span class="n">rindex</span><span class="p">(</span><span class="s1">&#39;mpl&#39;</span><span class="p">)</span>
<span class="k">print</span><span class="p">()</span>
</pre></div>


<div class="highlight"><pre><span></span>Example of str.find():

2
24
-1
Example of str.rfind():
56
56
-1
Example of str.index():
2
56
</pre></div>


<p><code>str.startswith()</code> 和 <code>str.endswith()</code> 是用来判断一个<em>字符串</em>是否以某个<em>子字符串</em>起始或者结束的：</p>
<div class="highlight"><pre><span></span><span class="n">s</span> <span class="o">=</span> <span class="s2">&quot;&quot;&quot;Simple is better than complex.</span>
<span class="s2">Complex is better than complicated.&quot;&quot;&quot;</span>

<span class="c1"># str.startswith(prefix[, start[, end]])</span>
<span class="k">print</span><span class="p">(</span><span class="s2">&quot;s.lower().startswith(&#39;S&#39;):&quot;</span><span class="p">,</span> \
      <span class="n">s</span><span class="o">.</span><span class="n">lower</span><span class="p">()</span><span class="o">.</span><span class="n">startswith</span><span class="p">(</span><span class="s1">&#39;S&#39;</span><span class="p">))</span>
<span class="k">print</span><span class="p">(</span><span class="s2">&quot;s.lower().startswith(&#39;b&#39;, 10):&quot;</span><span class="p">,</span> \
      <span class="n">s</span><span class="o">.</span><span class="n">lower</span><span class="p">()</span><span class="o">.</span><span class="n">startswith</span><span class="p">(</span><span class="s1">&#39;b&#39;</span><span class="p">,</span> <span class="mi">10</span><span class="p">))</span>
<span class="k">print</span><span class="p">(</span><span class="s2">&quot;s.lower().startswith(&#39;e&#39;, 11, 20):&quot;</span><span class="p">,</span> \
      <span class="n">s</span><span class="o">.</span><span class="n">lower</span><span class="p">()</span><span class="o">.</span><span class="n">startswith</span><span class="p">(</span><span class="s1">&#39;e&#39;</span><span class="p">,</span> <span class="mi">11</span><span class="p">,</span> <span class="mi">20</span><span class="p">))</span>

<span class="c1"># str.endswith(suffix[, start[, end]])</span>
<span class="k">print</span><span class="p">(</span><span class="s2">&quot;s.lower().endswith(&#39;.&#39;):&quot;</span><span class="p">,</span> \
      <span class="n">s</span><span class="o">.</span><span class="n">lower</span><span class="p">()</span><span class="o">.</span><span class="n">endswith</span><span class="p">(</span><span class="s1">&#39;.&#39;</span><span class="p">))</span>
<span class="k">print</span><span class="p">(</span><span class="s2">&quot;s.lower().endswith(&#39;.&#39;, 10):&quot;</span><span class="p">,</span> \
      <span class="n">s</span><span class="o">.</span><span class="n">lower</span><span class="p">()</span><span class="o">.</span><span class="n">endswith</span><span class="p">(</span><span class="s1">&#39;.&#39;</span><span class="p">,</span> <span class="mi">10</span><span class="p">))</span>
<span class="k">print</span><span class="p">(</span><span class="s2">&quot;s.lower().endswith(&#39;.&#39;, 10, 20):&quot;</span><span class="p">,</span> \
      <span class="n">s</span><span class="o">.</span><span class="n">lower</span><span class="p">()</span><span class="o">.</span><span class="n">endswith</span><span class="p">(</span><span class="s1">&#39;.&#39;</span><span class="p">,</span> <span class="mi">10</span><span class="p">,</span> <span class="mi">20</span><span class="p">))</span>

<span class="c1"># 好玩：中国人一不小心就会把这两个函数写成或者记成</span>
<span class="c1"># startwith() 和 endwith() —— 少写一个 s!</span>
</pre></div>


<div class="highlight"><pre><span></span>s.lower().startswith(&#39;S&#39;): False
s.lower().startswith(&#39;b&#39;, 10): True
s.lower().startswith(&#39;e&#39;, 11, 20): True
s.lower().endswith(&#39;.&#39;): True
s.lower().endswith(&#39;.&#39;, 10): True
s.lower().endswith(&#39;.&#39;, 10, 20): False
</pre></div>


<p>为了找到位置而进行搜索之前，你可能经常需要事先确认需要寻找的字符串在寻找对象中是否存在，这个时候，可以用 <code>in</code> 操作符：</p>
<div class="highlight"><pre><span></span><span class="n">s</span> <span class="o">=</span> <span class="s2">&quot;&quot;&quot;Simple is better than complex.</span>
<span class="s2">Complex is better than complicated.&quot;&quot;&quot;</span>
<span class="c1"># 如果你只想知道 “有没有”，而无需知道 “在哪里”，那么可以用：</span>
<span class="k">print</span><span class="p">(</span><span class="s1">&#39;mpl&#39;</span> <span class="ow">in</span> <span class="n">s</span><span class="p">)</span>
</pre></div>


<div class="highlight"><pre><span></span>True
</pre></div>


<p>能搜索，就应该能替换 —— <code>str.replace()</code>，它的函数说明是这样的：</p>
<blockquote>
<p><code>str.replace(old, new[, count])</code></p>
</blockquote>
<p>用 <code>new</code> 替换 <code>old</code>，替换 <code>count</code> 个实例（实例：exmpale，每次处理的对象就是实例，即具体的操作对象），其中，<code>count</code> 这个参数是可选的。</p>
<div class="highlight"><pre><span></span><span class="n">s</span> <span class="o">=</span> <span class="s2">&quot;&quot;&quot;Simple is better than complex.</span>
<span class="s2">Complex is better than complicated.&quot;&quot;&quot;</span>

<span class="c1"># str.startswith(prefix[, start[, end]])</span>
<span class="k">print</span><span class="p">(</span><span class="s2">&quot;s.lower().replace(&#39;mp&#39;, &#39;[ ]&#39;, 2):</span><span class="se">\n</span><span class="s2">&quot;</span><span class="p">)</span>
<span class="k">print</span><span class="p">(</span><span class="n">s</span><span class="o">.</span><span class="n">lower</span><span class="p">()</span><span class="o">.</span><span class="n">replace</span><span class="p">(</span><span class="s1">&#39;mp&#39;</span><span class="p">,</span> <span class="s1">&#39;[ ]&#39;</span><span class="p">,</span> <span class="mi">2</span><span class="p">))</span>
</pre></div>


<div class="highlight"><pre><span></span>s.lower().replace(&#39;mp&#39;, &#39;[ ]&#39;, 2):

si[ ]le is better than co[ ]lex.
complex is better than complicated.
</pre></div>


<p>另外，还有个专门替换 TAB（<code>\t</code>）的 Method，</p>
<blockquote>
<p><code>str.expandtabs( tabsize=8)</code></p>
</blockquote>
<p>它的作用非常简单，就是把字符串中的 TAB（<code>\t</code>）替换成空格，默认是替换成 <code>8</code> 个空格 —— 当然你也可以指定究竟替换成几个空格</p>
<div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">IPython.core.interactiveshell</span> <span class="kn">import</span> <span class="n">InteractiveShell</span>
<span class="n">InteractiveShell</span><span class="o">.</span><span class="n">ast_node_interactivity</span> <span class="o">=</span> <span class="s2">&quot;all&quot;</span>

<span class="c1"># str.expandtabs(tabsize=8)</span>
<span class="n">s</span> <span class="o">=</span> <span class="s2">&quot;Special</span><span class="se">\t</span><span class="s2">cases</span><span class="se">\t</span><span class="s2">aren&#39;t</span><span class="se">\t</span><span class="s2">special</span><span class="se">\t</span><span class="s2">enough</span><span class="se">\t</span><span class="s2">to</span><span class="se">\t</span><span class="s2">break</span><span class="se">\t</span><span class="s2">the</span><span class="se">\t</span><span class="s2">rules.&quot;</span>
<span class="n">s</span><span class="o">.</span><span class="n">expandtabs</span><span class="p">()</span>
<span class="n">s</span><span class="o">.</span><span class="n">expandtabs</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span>
</pre></div>


<div class="highlight"><pre><span></span>&quot;Special cases   aren&#39;t  special enough  to      break   the     rules.&quot;
&quot;Special cases aren&#39;t  special enough  to  break the rules.&quot;
</pre></div>


<h3>去除子字符</h3>
<blockquote>
<p><code>str.strip([chars])</code></p>
</blockquote>
<p>它最常用的场景是去除一个字符串首尾的所有空白，包括空格、TAB、换行符等等。</p>
<div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">IPython.core.interactiveshell</span> <span class="kn">import</span> <span class="n">InteractiveShell</span>
<span class="n">InteractiveShell</span><span class="o">.</span><span class="n">ast_node_interactivity</span> <span class="o">=</span> <span class="s2">&quot;all&quot;</span>

<span class="n">s</span> <span class="o">=</span> <span class="s2">&quot;</span><span class="se">\r</span><span class="s2"> </span><span class="se">\t</span><span class="s2"> Simple is better than complex.    </span><span class="se">\t</span><span class="s2"> </span><span class="se">\n</span><span class="s2">&quot;</span>
<span class="n">s</span>
<span class="n">s</span><span class="o">.</span><span class="n">strip</span><span class="p">()</span>
</pre></div>


<div class="highlight"><pre><span></span>&#39;\r \t Simple is better than complex.    \t \n&#39;

&#39;Simple is better than complex.&#39;
</pre></div>


<p>但是，如果给定了一个字符串作为参数，那么参数字符串中的所有字母都会被当做需要从首尾剔除的对象，直到新的首尾字母不包含在参数中，就会停止剔除：</p>
<div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">IPython.core.interactiveshell</span> <span class="kn">import</span> <span class="n">InteractiveShell</span>
<span class="n">InteractiveShell</span><span class="o">.</span><span class="n">ast_node_interactivity</span> <span class="o">=</span> <span class="s2">&quot;all&quot;</span>

<span class="n">s</span> <span class="o">=</span> <span class="s2">&quot;Simple is better than complex.&quot;</span>
<span class="n">s</span>
<span class="n">s</span><span class="o">.</span><span class="n">strip</span><span class="p">(</span><span class="s1">&#39;Six.p&#39;</span><span class="p">)</span>    <span class="c1"># p 全部处理完之后，p 并不在首尾，所以原字符串中的 p 字母不受影响；</span>
<span class="n">s</span><span class="o">.</span><span class="n">strip</span><span class="p">(</span><span class="s1">&#39;pSix.mle&#39;</span><span class="p">)</span> <span class="c1"># 这一次，首尾的 p 被处理了…… 参数中的字符顺序对结果没有影响，换成 Sipx.mle 也一样……</span>
</pre></div>


<div class="highlight"><pre><span></span>&#39;Simple is better than complex.&#39;
&#39;mple is better than comple&#39;
&#39; is better than co&#39;
</pre></div>


<p>还可以只对左侧处理，<code>str.lstrip()</code> 或者只对右侧处理，<code>str.rstrip()</code></p>
<div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">IPython.core.interactiveshell</span> <span class="kn">import</span> <span class="n">InteractiveShell</span>
<span class="n">InteractiveShell</span><span class="o">.</span><span class="n">ast_node_interactivity</span> <span class="o">=</span> <span class="s2">&quot;all&quot;</span>

<span class="c1"># str.lstrip([chars])</span>
<span class="n">s</span> <span class="o">=</span> <span class="s2">&quot;Simple is better than complex.&quot;</span>
<span class="n">s</span>
<span class="n">s</span><span class="o">.</span><span class="n">lstrip</span><span class="p">(</span><span class="s1">&#39;Six.p&#39;</span><span class="p">)</span>    <span class="c1"># p 全部处理完之后，p 并不在首部，所以原字符串中的 p 字母不受影响；</span>
<span class="n">s</span><span class="o">.</span><span class="n">lstrip</span><span class="p">(</span><span class="s1">&#39;pSix.mle&#39;</span><span class="p">)</span> <span class="c1"># 这一次，首部的 p 被处理了…… 参数中的字符顺序对结果没有影响，换成 Sipx.mle 也一样……</span>
</pre></div>


<div class="highlight"><pre><span></span>&#39;Simple is better than complex.&#39;
&#39;mple is better than complex.&#39;
&#39; is better than complex.&#39;
</pre></div>


<div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">IPython.core.interactiveshell</span> <span class="kn">import</span> <span class="n">InteractiveShell</span>
<span class="n">InteractiveShell</span><span class="o">.</span><span class="n">ast_node_interactivity</span> <span class="o">=</span> <span class="s2">&quot;all&quot;</span>

<span class="c1"># str.rstrip([chars])</span>
<span class="n">s</span> <span class="o">=</span> <span class="s2">&quot;Simple is better than complex.&quot;</span>
<span class="n">s</span>
<span class="n">s</span><span class="o">.</span><span class="n">rstrip</span><span class="p">(</span><span class="s1">&#39;Six.p&#39;</span><span class="p">)</span>    <span class="c1"># p 全部处理完之后，p 并不在尾部，所以原字符串中的 p 字母不受影响；</span>
<span class="n">s</span><span class="o">.</span><span class="n">rstrip</span><span class="p">(</span><span class="s1">&#39;pSix.mle&#39;</span><span class="p">)</span> <span class="c1"># 这一次，尾部的 p 被处理了…… 参数中的字符顺序对结果没有影响，换成 Sipx.mle 也一样……</span>
</pre></div>


<div class="highlight"><pre><span></span>&#39;Simple is better than complex.&#39;
&#39;Simple is better than comple&#39;
&#39;Simple is better than co&#39;
</pre></div>


<h3>拆分字符串</h3>
<p>在计算机里，数据一般保存在文件之中。计算机擅长处理的是 “格式化数据”，即，这些数据按照一定的格式排列 —— 电子表格、数据库，就是一种保存方式。Microsoft 的 Excel 和 Apple 的 Numbers，都可以将表格导出为 <code>.csv</code> 文件。这是文本文件，里面的每一行可能由多个数据构成，数据之间用 <code>,</code>（或 <code>;</code>、<code>\t</code>）分隔：</p>
<div class="highlight"><pre><span></span>Name,Age,Location
John,18,New York
Mike,22,San Francisco
Janny,25,Miami
Sunny,21,Shanghai
</pre></div>


<p>文本文件中的这样一段内容，被读进来之后，保存在某个变量，那么，那个变量的值长成这个样子：</p>
<blockquote>
<p><code>'Name,Age,Location\nJohn,18,New York\nMike,22,San Francisco\nJanny,25,Miami\nSunny,21,Shanghai'</code></p>
</blockquote>
<p>我们可以对这样的字符串进行很多操作，最常用的比如，<code>str.splitlines()</code>, <code>str.split()</code>；还有个 <code>str.partition()</code>，有空的人可以去<a href="https://docs.python.org/3/library/stdtypes.html#str.partition">官方文档</a>看看说明。</p>
<p><code>str.splitlines()</code> 返回的是个列表（List）—— 这又是一个前面曾简要提起过，但会在后面的章节才能详细讲解的概念 —— 由被拆分的每一行作为其中的元素。</p>
<div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">IPython.core.interactiveshell</span> <span class="kn">import</span> <span class="n">InteractiveShell</span>
<span class="n">InteractiveShell</span><span class="o">.</span><span class="n">ast_node_interactivity</span> <span class="o">=</span> <span class="s2">&quot;all&quot;</span>

<span class="n">s</span> <span class="o">=</span> <span class="s2">&quot;&quot;&quot;Name,Age,Location</span>
<span class="s2">John,18,New York</span>
<span class="s2">Mike,22,San Francisco</span>
<span class="s2">Janny,25,Miami</span>
<span class="s2">Sunny,21,Shanghai&quot;&quot;&quot;</span>

<span class="n">s</span>                 <span class="c1"># s 被打印出来的时候，\n 都被转换成换行了</span>
<span class="n">s</span><span class="o">.</span><span class="n">splitlines</span><span class="p">()</span>    <span class="c1"># 注意输出结果前后的方括号，[]，表示这个返回结果是一个 List</span>
</pre></div>


<div class="highlight"><pre><span></span>&#39;Name,Age,Location\nJohn,18,New York\nMike,22,San Francisco\nJanny,25,Miami\nSunny,21,Shanghai&#39;

[&#39;Name,Age,Location&#39;,
 &#39;John,18,New York&#39;,
 &#39;Mike,22,San Francisco&#39;,
 &#39;Janny,25,Miami&#39;,
 &#39;Sunny,21,Shanghai&#39;]
</pre></div>


<p><code>str.split()</code>, 是将一个字符串，根据分隔符进行拆分：</p>
<blockquote>
<p><code>str.split(sep=None, maxsplit=-1)</code></p>
</blockquote>
<div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">IPython.core.interactiveshell</span> <span class="kn">import</span> <span class="n">InteractiveShell</span>
<span class="n">InteractiveShell</span><span class="o">.</span><span class="n">ast_node_interactivity</span> <span class="o">=</span> <span class="s2">&quot;all&quot;</span>

<span class="n">s</span> <span class="o">=</span> <span class="s2">&quot;&quot;&quot;Name,Age,Location</span>
<span class="s2">John,18,New York</span>
<span class="s2">Mike,22,San Francisco</span>
<span class="s2">Janny,25,Miami</span>
<span class="s2">Sunny,21,Shanghai&quot;&quot;&quot;</span>

<span class="n">r</span> <span class="o">=</span> <span class="n">s</span><span class="o">.</span><span class="n">splitlines</span><span class="p">()[</span><span class="mi">2</span><span class="p">]</span>   <span class="c1"># 取出返回列表中索引值为 2 的那一行</span>
<span class="n">r</span>
<span class="n">r</span><span class="o">.</span><span class="n">split</span><span class="p">()</span>               <span class="c1"># 如果没有给 str.split() 传递参数，那么默认为用 None 分割（各种空白，比如，\t 和 \r 都被当作 None）</span>
<span class="n">r</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="n">sep</span><span class="o">=</span><span class="s1">&#39;,&#39;</span><span class="p">)</span>
<span class="n">r</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s1">&#39;,&#39;</span><span class="p">)</span>            <span class="c1"># 上一行可以这样写。</span>

<span class="n">r</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="n">sep</span><span class="o">=</span><span class="s1">&#39;,&#39;</span><span class="p">,</span> <span class="n">maxsplit</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>  <span class="c1"># 第二个参数指定拆分几次</span>
<span class="c1"># r.split(sep=&#39;,&#39;, 1)         # 上一行不能这样写。</span>
<span class="n">r</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="n">sep</span><span class="o">=</span><span class="s1">&#39;,&#39;</span><span class="p">,</span> <span class="n">maxsplit</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span>  <span class="c1"># 0 次，即不拆分</span>
<span class="n">r</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="n">sep</span><span class="o">=</span><span class="s1">&#39;,&#39;</span><span class="p">,</span> <span class="n">maxsplit</span><span class="o">=-</span><span class="mi">1</span><span class="p">)</span> <span class="c1"># 默认值是 -1，拆分全部</span>
</pre></div>


<div class="highlight"><pre><span></span>&#39;Mike,22,San Francisco&#39;
[&#39;Mike,22,San&#39;, &#39;Francisco&#39;]
[&#39;Mike&#39;, &#39;22&#39;, &#39;San Francisco&#39;]
[&#39;Mike&#39;, &#39;22&#39;, &#39;San Francisco&#39;]
[&#39;Mike&#39;, &#39;22,San Francisco&#39;]
[&#39;Mike,22,San Francisco&#39;]
[&#39;Mike&#39;, &#39;22&#39;, &#39;San Francisco&#39;]
</pre></div>


<h3>拼接字符串</h3>
<p><code>str.join()</code> 是将来非常常用的，它的官方文档说明却很少：</p>
<blockquote>
<p><code>str.join(_iterable_)</code></p>
<p>Return a string which is the concatenation of the strings in iterable. A <em><a href="https://docs.python.org/3/library/exceptions.html#TypeError"><code>TypeError</code></a></em> will be raised if there are any non-string values in iterable, including <a href="https://docs.python.org/3/library/stdtypes.html#bytes"><code>bytes</code></a> objects. The separator between elements is the string providing this method.</p>
</blockquote>
<p>它接收的参数是 <a href="https://docs.python.org/3/glossary.html#term-iterable">iterable</a>，虽然你还没办法知道 iterable 究竟是什么，但这个 Method 的例子貌似可以看懂（可能你会产生 “那个方括号究竟是干什么的” 的疑问，也可能对前面章节提到的列表还有印象）：</p>
<div class="highlight"><pre><span></span><span class="n">s</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span>
<span class="n">t</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;P&#39;</span><span class="p">,</span> <span class="s1">&#39;y&#39;</span><span class="p">,</span> <span class="s1">&#39;t&#39;</span><span class="p">,</span> <span class="s1">&#39;h&#39;</span><span class="p">,</span> <span class="s1">&#39;o&#39;</span><span class="p">,</span> <span class="s1">&#39;n&#39;</span><span class="p">]</span>
<span class="n">s</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">t</span><span class="p">)</span>
</pre></div>


<div class="highlight"><pre><span></span>&#39;Python&#39;
</pre></div>


<h3>字符串排版</h3>
<p>将字符串居中放置 —— 前提是设定整行的长度：</p>
<blockquote>
<p><code>str.center(width[, fillchar])</code></p>
</blockquote>
<p>注意，第 2 个参数可选，且只接收单个字符 —— <code>char</code> 是 <em>character</em> 的缩写。</p>
<div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">IPython.core.interactiveshell</span> <span class="kn">import</span> <span class="n">InteractiveShell</span>
<span class="n">InteractiveShell</span><span class="o">.</span><span class="n">ast_node_interactivity</span> <span class="o">=</span> <span class="s2">&quot;all&quot;</span>

<span class="n">s</span> <span class="o">=</span> <span class="s1">&#39;Sparse is better than dense!&#39;</span>
<span class="n">s</span><span class="o">.</span><span class="n">title</span><span class="p">()</span><span class="o">.</span><span class="n">center</span><span class="p">(</span><span class="mi">60</span><span class="p">)</span>
<span class="n">s</span><span class="o">.</span><span class="n">title</span><span class="p">()</span><span class="o">.</span><span class="n">center</span><span class="p">(</span><span class="mi">60</span><span class="p">,</span> <span class="s1">&#39;=&#39;</span><span class="p">)</span>
<span class="n">s</span><span class="o">.</span><span class="n">title</span><span class="p">()</span><span class="o">.</span><span class="n">center</span><span class="p">(</span><span class="mi">10</span><span class="p">)</span> <span class="c1"># 如果宽度参数小于字符串长度，则返回原字符串</span>

<span class="n">s</span> <span class="o">=</span> <span class="s1">&#39;Sparse is better than dense!&#39;</span>
<span class="n">s</span><span class="o">.</span><span class="n">title</span><span class="p">()</span><span class="o">.</span><span class="n">rjust</span><span class="p">(</span><span class="mi">60</span><span class="p">)</span>
<span class="n">s</span><span class="o">.</span><span class="n">title</span><span class="p">()</span><span class="o">.</span><span class="n">rjust</span><span class="p">(</span><span class="mi">60</span><span class="p">,</span> <span class="s1">&#39;.&#39;</span><span class="p">)</span>
</pre></div>


<div class="highlight"><pre><span></span>&#39;                Sparse Is Better Than Dense!                &#39;

&#39;================Sparse Is Better Than Dense!================&#39;

&#39;Sparse Is Better Than Dense!&#39;

&#39;                                Sparse Is Better Than Dense!&#39;

&#39;................................Sparse Is Better Than Dense!&#39;
</pre></div>


<p>将字符串靠左或者靠右对齐放置：</p>
<blockquote>
<ul>
<li><code>str.ljust(width)</code></li>
<li><code>str.rjust(width)</code></li>
</ul>
</blockquote>
<p>另外，还有个字符串 Method 是，将字符串转换成左侧由 <code>0</code> 填充的指定长度字符串。例如，这在批量生成文件名的时候就很有用……</p>
<div class="highlight"><pre><span></span><span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">11</span><span class="p">):</span>
    <span class="n">filename</span> <span class="o">=</span> <span class="nb">str</span><span class="p">(</span><span class="n">i</span><span class="p">)</span><span class="o">.</span><span class="n">zfill</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span> <span class="o">+</span> <span class="s1">&#39;.mp3&#39;</span>
    <span class="k">print</span><span class="p">(</span><span class="n">filename</span><span class="p">)</span>
</pre></div>


<div class="highlight"><pre><span></span>001.mp3
002.mp3
003.mp3
004.mp3
005.mp3
006.mp3
007.mp3
008.mp3
009.mp3
010.mp3
</pre></div>


<h3>格式化字符串</h3>
<p>所谓对字符串进行格式化，指的是将特定变量插入字符串特定位置的过程。常用的 Methods 有两个，一个是 <code>str.format()</code>，另外一个是 <code>f-string</code>。</p>
<h4>使用 str.format()</h4>
<p>这个 Method 的<a href="https://docs.python.org/3/library/stdtypes.html#str.format">官方文档说明</a>，你现在是死活看不懂的：</p>
<blockquote>
<p><code>str.format(*args, **kwargs)</code></p>
</blockquote>
<p>参数前面多了个 <code>*</code>…… 没办法，现在讲不清楚，讲了也听不明白…… 先跳过，以下只关注怎么用这个 Method。</p>
<p>它的作用是：</p>
<blockquote>
<ul>
<li>在一个字符串中，插入一个或者多个占位符 —— 用大括号 <code>{}</code> 括起来；</li>
<li>而后将 <code>str.format()</code> 相应的参数，依次插入占位符中；</li>
</ul>
</blockquote>
<p>占位符中可以使用由零开始的索引。</p>
<div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">IPython.core.interactiveshell</span> <span class="kn">import</span> <span class="n">InteractiveShell</span>
<span class="n">InteractiveShell</span><span class="o">.</span><span class="n">ast_node_interactivity</span> <span class="o">=</span> <span class="s2">&quot;all&quot;</span>

<span class="n">name</span> <span class="o">=</span> <span class="s1">&#39;John&#39;</span>
<span class="n">age</span> <span class="o">=</span> <span class="mi">25</span>
<span class="s1">&#39;{} is {} years old.&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">name</span><span class="p">,</span> <span class="n">age</span><span class="p">)</span>
<span class="c1"># 不写占位符索引就默认每个占位符的索引从第一个开始是 0, 1, 2 ...（占位符数量 - 1)</span>
<span class="c1"># &#39;{} {}&#39;.format(a, b) 和 &#39;{0} {1}&#39;.format(a, b) 是一样的。</span>

<span class="c1"># &#39;{0} is {2} years old.&#39;.format(name, age)</span>
<span class="c1"># 这一句会报错，因为 2 超出实际参数索引极限</span>

<span class="c1"># 两个连续使用的大括号，不被认为是占位符；且只打印出一对大括号</span>
<span class="s2">&quot;Are you {0}? :-{{+}}&quot;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">name</span><span class="p">)</span>

<span class="c1"># &quot;%s is %d years old.&quot; % (name, age)</span>
<span class="c1"># 上一行这是兼容 Python 2 的老式写法，可以从此忽略……</span>

<span class="c1"># str.fomrat() 里可以直接写表达式……</span>
<span class="s1">&#39;{} is a grown up? {}&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">name</span><span class="p">,</span> <span class="n">age</span> <span class="o">&gt;=</span> <span class="mi">18</span><span class="p">)</span>
</pre></div>


<div class="highlight"><pre><span></span><span class="s s-Atom">&#39;John is 25 years old.&#39;</span>
<span class="s s-Atom">&#39;Are you John? :-{+}&#39;</span>
<span class="s s-Atom">&#39;John is a grown up? True&#39;</span>
</pre></div>


<h4>使用 f-string</h4>
<p><em>f-string</em> 与 <code>str.format()</code> 的功用差不多，只是写法简洁一些 —— 在字符串标示之前加上一个字母 <code>f</code>：</p>
<div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">IPython.core.interactiveshell</span> <span class="kn">import</span> <span class="n">InteractiveShell</span>
<span class="n">InteractiveShell</span><span class="o">.</span><span class="n">ast_node_interactivity</span> <span class="o">=</span> <span class="s2">&quot;all&quot;</span>

<span class="c1"># https://docs.python.org/3/library/stdtypes.html#printf-style-bytes-formatting</span>
<span class="c1"># f-string</span>

<span class="n">name</span> <span class="o">=</span> <span class="s1">&#39;John&#39;</span>
<span class="n">age</span> <span class="o">=</span> <span class="mi">25</span>
<span class="n">f</span><span class="s1">&#39;{name} is {age} years old.&#39;</span>
<span class="n">f</span><span class="s1">&#39;{name} is a grown up? {age &gt;= 18}&#39;</span>
</pre></div>


<div class="highlight"><pre><span></span>&#39;John is 25 years old.&#39;
&#39;John is a grown up? True&#39;
</pre></div>


<p>只不过，str.format() 的用法中，索引顺序可以任意指定，于是相对更为灵活，下面的例子只是为了演示参数位置可以任意指定：</p>
<div class="highlight"><pre><span></span><span class="n">name</span> <span class="o">=</span> <span class="s1">&#39;John&#39;</span>
<span class="n">age</span> <span class="o">=</span> <span class="mi">25</span>
<span class="s1">&#39;{1} is {0} years old.&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">name</span><span class="p">,</span> <span class="n">age</span><span class="p">)</span>
</pre></div>


<div class="highlight"><pre><span></span>&#39;25 is John years old.&#39;
</pre></div>


<h3>字符串属性</h3>
<p>字符串还有一系列的 Methods，返回的是布尔值，用来判断字符串的构成属性：</p>
<div class="highlight"><pre><span></span><span class="c1"># str.isalnum()</span>
<span class="k">print</span><span class="p">(</span><span class="s2">&quot;&#39;1234567890&#39;.isalnum():&quot;</span><span class="p">,</span> \
      <span class="s1">&#39;1234567890&#39;</span><span class="o">.</span><span class="n">isalnum</span><span class="p">())</span> <span class="c1"># &#39;3.14&#39;.isalnum() 返回的是 False</span>

<span class="c1"># str.isalpha()</span>
<span class="k">print</span><span class="p">(</span><span class="s2">&quot;&#39;abcdefghij&#39;.isalpha():&quot;</span><span class="p">,</span> \
      <span class="s1">&#39;abcdefghij&#39;</span><span class="o">.</span><span class="n">isalpha</span><span class="p">())</span>

<span class="c1"># str.isascii()</span>
<span class="k">print</span><span class="p">(</span><span class="s2">&quot;&#39;山巅一寺一壶酒&#39;.isascii():&quot;</span><span class="p">,</span> \
      <span class="s1">&#39;山巅一寺一壶酒&#39;</span><span class="o">.</span><span class="n">isascii</span><span class="p">())</span>

<span class="c1"># str.isdecimal()</span>
<span class="k">print</span><span class="p">(</span><span class="s2">&quot;&#39;0.123456789&#39;.isdecimal():&quot;</span><span class="p">,</span> \
      <span class="s1">&#39;0.1234567890&#39;</span><span class="o">.</span><span class="n">isdecimal</span><span class="p">())</span>

<span class="c1"># str.isdigit()</span>
<span class="k">print</span><span class="p">(</span><span class="s2">&quot;&#39;0.123456789&#39;.isdigit():&quot;</span><span class="p">,</span> \
      <span class="s1">&#39;0.1234567890&#39;</span><span class="o">.</span><span class="n">isdigit</span><span class="p">())</span>       <span class="c1">#  注意，如果字符串是 identifier，返回值也是 False</span>

<span class="c1"># str.isnumeric()</span>
<span class="k">print</span><span class="p">(</span><span class="s2">&quot;&#39;0.123456789&#39;.isnumeric():&quot;</span><span class="p">,</span> \
      <span class="s1">&#39;0.1234567890&#39;</span><span class="o">.</span><span class="n">isnumeric</span><span class="p">())</span>

<span class="c1"># str.islower()</span>
<span class="k">print</span><span class="p">(</span><span class="s2">&quot;&#39;Continue&#39;.islower():&quot;</span><span class="p">,</span> \
      <span class="s1">&#39;Continue&#39;</span><span class="o">.</span><span class="n">islower</span><span class="p">())</span>

<span class="c1"># str.isupper()</span>
<span class="k">print</span><span class="p">(</span><span class="s2">&quot;&#39;Simple Is Better Than Complex&#39;.isupper():&quot;</span><span class="p">,</span> \
      <span class="s1">&#39;Simple Is Better Than Complex&#39;</span><span class="o">.</span><span class="n">isupper</span><span class="p">())</span>

<span class="c1"># str.istitle()</span>
<span class="k">print</span><span class="p">(</span><span class="s2">&quot;&#39;Simple Is Better Than Complex&#39;.istitle():&quot;</span><span class="p">,</span> \
      <span class="s1">&#39;Simple Is Better Than Complex&#39;</span><span class="o">.</span><span class="n">istitle</span><span class="p">())</span>

<span class="c1"># str.isprintable()</span>
<span class="k">print</span><span class="p">(</span><span class="s2">&quot;&#39;</span><span class="se">\t</span><span class="s2">&#39;.isprintable():&quot;</span><span class="p">,</span> \
      <span class="s1">&#39;</span><span class="se">\t</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">isprintable</span><span class="p">())</span>

<span class="c1"># str.isspace()</span>
<span class="k">print</span><span class="p">(</span><span class="s2">&quot;&#39;</span><span class="se">\t</span><span class="s2">&#39;.isspace():&quot;</span><span class="p">,</span> \
      <span class="s1">&#39;</span><span class="se">\t</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">isspace</span><span class="p">())</span>

<span class="c1"># str.isidentifier()</span>
<span class="k">print</span><span class="p">(</span><span class="s2">&quot;&#39;for&#39;.isidentifier():&quot;</span><span class="p">,</span> \
      <span class="s1">&#39;for&#39;</span><span class="o">.</span><span class="n">isidentifier</span><span class="p">())</span>
</pre></div>


<div class="highlight"><pre><span></span>&#39;1234567890&#39;.isalnum(): True
&#39;abcdefghij&#39;.isalpha(): True
&#39;山巅一寺一壶酒&#39;.isascii(): False
&#39;0.123456789&#39;.isdecimal(): False
&#39;0.123456789&#39;.isdigit(): False
&#39;0.123456789&#39;.isnumeric(): False
&#39;Continue&#39;.islower(): False
&#39;Simple Is Better Than Complex&#39;.isupper(): False
&#39;Simple Is Better Than Complex&#39;.istitle(): True
&#39;   &#39;.isprintable(): False
&#39;   &#39;.isspace(): True
&#39;for&#39;.isidentifier(): True
</pre></div>


<h2>总结</h2>
<p>这一章节显得相当繁杂。然而，这一章和下一章（关于容器），都是 “用来锻炼自己耐心的好材料”……</p>
<p>不过，若是自己动手整理成一个表格，总结归纳一下这一章节的内容，你就会发现其实没多繁杂，总之就还是那点事，怎么处理字符串？用操作符、用内建函数，用 Methods。只不过，字符串的操作符和数值的操作符不一样 —— 类型不一样，操作符就当然不一样了么！—— 最不一样的地方是，字符串是有序容器的一种，所以，它有索引，所以可以根据索引提取…… 至于剩下的么，就是很常规的了，用函数处理，用 Methods 处理，只不过，Methods 相对多了一点而已。</p>
<p>整理成表格之后，就会发现想要全部记住其实并没多难……</p>
<blockquote>
<ul>
<li>为了表格在一屏中可以正确显示，本来应该规规矩矩写 <code>str.xxx</code>，但写成了 <code>s.xxx</code>……</li>
<li>另外，操作那一行，为了分类记忆方便，把 <code>len()</code> 和 <code>s.join()</code> 也放进去了……</li>
</ul>
</blockquote>
<p><img alt="123" src="https://raw.githubusercontent.com/selfteaching/the-craft-of-selfteaching/master/images/string-concepts.png?raw=true"></p>
<p>“记住” 的方法并不是马上就只盯着表格看…… 正确方法是反复阅读这一章内容中的代码，并逐一运行，查看输出结果；还要顺手改改看看，多多体会。多次之后，再看着表格回忆知识点，直到牢记为止。</p>
<h2>为什么数值没有像字符串值这样详细论述？</h2>
<p>上一章中，我们概括地讲了各种类型的值的运算。而后并没有继续深入讲解数字的运算，而是直接 “跳” 到了这一章关于字符串的内容。其实，只要一张表格和一个列表就足够了（因为之前零零散散都讲过）：</p>
<p>Python 针对数字常用的操作符和内建函数，按照<strong>优先级</strong>从低到高排列：</p>
<table>
<thead>
<tr>
<th>名称</th>
<th>操作</th>
<th>结果</th>
<th>官方文档链接</th>
</tr>
</thead>
<tbody>
<tr>
<td>加</td>
<td><code>1 + 2</code></td>
<td>3</td>
<td></td>
</tr>
<tr>
<td>减</td>
<td><code>2 - 1</code></td>
<td>1</td>
<td></td>
</tr>
<tr>
<td>乘</td>
<td><code>3 * 5</code></td>
<td>15</td>
<td></td>
</tr>
<tr>
<td>除</td>
<td><code>6 / 2</code></td>
<td>3.0</td>
<td></td>
</tr>
<tr>
<td>商</td>
<td><code>7 // 3</code></td>
<td>2</td>
<td></td>
</tr>
<tr>
<td>余</td>
<td><code>7 % 3</code></td>
<td>1</td>
<td></td>
</tr>
<tr>
<td>负</td>
<td><code>-6</code></td>
<td>-6</td>
<td></td>
</tr>
<tr>
<td>正</td>
<td><code>+6</code></td>
<td>6</td>
<td></td>
</tr>
<tr>
<td>绝对值</td>
<td><code>abs(-1)</code></td>
<td>1</td>
<td><a href="https://docs.python.org/3/library/functions.html#abs"><code>abs()</code></a></td>
</tr>
<tr>
<td>转换为整数</td>
<td><code>int(3.14)</code></td>
<td>3</td>
<td><a href="https://docs.python.org/3/library/functions.html#int"><code>int()</code></a></td>
</tr>
<tr>
<td>转换为浮点数</td>
<td><code>float(3)</code></td>
<td>3.0</td>
<td><a href="https://docs.python.org/3/library/functions.html#float"><code>float()</code></a></td>
</tr>
<tr>
<td>商余</td>
<td><code>divmod(7, 3)</code></td>
<td>2, 1</td>
<td><a href="https://docs.python.org/3/library/functions.html#divmod"><code>divmod()</code></a></td>
</tr>
<tr>
<td>幂</td>
<td><code>pow(2, 10)</code></td>
<td>1024</td>
<td><a href="https://docs.python.org/3/library/functions.html#pow"><code>pow()</code></a></td>
</tr>
<tr>
<td>幂</td>
<td><code>3 ** 2</code></td>
<td>9</td>
<td></td>
</tr>
</tbody>
</table>
<p>Python 用来处理数值的内建函数：</p>
<blockquote>
<ul>
<li><code>abs(n)</code> 函数返回参数 <code>n</code> 的<em>绝对值</em>；</li>
<li><code>int(n)</code> 用来将<em>浮点数字</em> <code>n</code> 转换成<em>整数</em>；</li>
<li><code>float(n)</code> 用来将<em>整数</em> <code>n</code> 转换成<em>浮点数字</em>；</li>
<li><code>divmod(n, m)</code> 用来计算  <code>n</code>  除以  <code>m</code>，返回两个整数，一个是<em>商</em>，另外一个是<em>余</em>；</li>
<li><code>pow(n, m)</code> 用来做乘方运算，返回 <code>n</code> 的 <code>m</code> <em>次方</em>；</li>
<li><code>round(n)</code> 返回离浮点数字 <code>n</code> 最近的那个<em>整数</em>。</li>
</ul>
</blockquote>
<p>Python 做更为复杂的数学计算的模块（Module）是 math module，参阅：</p>
<blockquote>
<p>https://docs.python.org/3/library/math.html</p>
</blockquote>
<hr>
<p><strong>脚注</strong></p>
<p><a name='fn1'>[1]</a>：请查阅 https://en.wikipedia.org/wiki/Unicode</p>
<p><a href='#fn1b'><small>↑Back to Content↑</small></a></p>
    </div><!-- /.entry-content -->

  </article>
</section>
        <section id="extras" class="body">
                <div class="blogroll">
                        <h2>blogroll</h2>
                        <ul>
                            <li><a href="http://getpelican.com/">Pelican</a></li>
                            <li><a href="http://python.org/">Python.org</a></li>
                            <li><a href="http://jinja.pocoo.org/">Jinja2</a></li>
                            <li><a href="#">You can modify those links in your config file</a></li>
                        </ul>
                </div><!-- /.blogroll -->
                <div class="social">
                        <h2>social</h2>
                        <ul>

                            <li><a href="#">You can add links in your config file</a></li>
                            <li><a href="#">Another social link</a></li>
                        </ul>
                </div><!-- /.social -->
        </section><!-- /#extras -->

        <footer id="contentinfo" class="body">
                <p>Powered by <a href="http://www.maxiaoan.com/">Maxiaoan</a></p>
        </footer><!-- /#contentinfo -->

</body>
</html>